package avicit.im.lantop.basic.reportmanager.action;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import avicit.cbb.tabledefine.service.api.CommTableManagerIntfsServiceApi;
import avicit.im.lantop.basic.reportmanager.service.api.ReportManagerServicesApi;
import avicit.platform6.core.context.ThreadContextHelper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import avicit.cbb.tabledefine.service.CommTableManagerIntfsService;
import avicit.im.lantop.basic.reportmanager.domain.LantopReportConfigDetails;
import avicit.im.lantop.basic.reportmanager.domain.LantopReportConfiguration;
import avicit.im.lantop.basic.reportmanager.domain.LantopReportField;
import avicit.im.lantop.basic.reportmanager.service.ReportManagerServices;
import avicit.platform6.api.sysuser.dto.SysUser;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.JsonUtils;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.dao.Paging;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import avicit.platform6.core.rest.msg.PageParameter;
import avicit.platform6.api.session.SessionHelper;

/**
 * <p>
 * 金航数码科技有限责任公司
 * </p>
 * <p>
 * 作者：张坚
 * </p>
 * <p>
 * 邮箱：18629436468@163.com
 * </p>
 * <p>
 * 创建时间： 2015-4-13 下午4:53:23
 * </p>
 * <p>
 * 类说明：报表配置控制器类
 * </p>
 * <p>
 * 修改记录：
 * </p>
 */
@Controller
@SuppressWarnings({"deprecation" })
@RequestMapping("/ReportFormConfigController")
public class ReportFormConfigController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ReportFormConfigController.class);

	@Autowired
	private CommTableManagerIntfsServiceApi commTableManagerIntfsService;

	@Resource
	private ReportManagerServicesApi reportManagerServices;

	/**
	 * 跳转到报表配置页面
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/toReportFormConfigJsp")
	public ModelAndView toReportFormConfigJsp(HttpServletRequest request) throws Exception {

		ModelAndView mav = new ModelAndView();

		String sysId = "LANTOP";
		String dialogId = request.getParameter("dialogId");

		// 获取与该模板相关的表名如果有多个则用, 分隔
		String resultDataSource = request.getParameter("resultDataSource");

		// 获取模板ID
		String templateId = request.getParameter("templateId");

		// GET请求需要转码
		String outPutFields = URLDecoder.decode(request.getParameter("outPutFields"), "utf-8");

		mav.addObject("dialogId", dialogId);
		mav.addObject("sysId", sysId);
		mav.addObject("outputFields", outPutFields);
		mav.addObject("templateId", templateId);
		mav.addObject("fieldsCount", outPutFields.split(",").length);
		mav.addObject("resultDataSource", resultDataSource);

		mav.setViewName("avicit/im/lantop/basic/reportmanager/ReportFormConfig");
		return mav;
	}

	/**
	 * 根据表ID获取模板配置的字段信息和未配置的字段
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/getTableList")
	@ResponseBody
	public Map<String,Object> getTableList(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String nodeId = request.getParameter("nodeId");
		// 与该模板相关的表, 模板ID
		String templateId = request.getParameter("templateId");
		String resultDataSource = request.getParameter("resultDataSource");
		String sysId = request.getParameter("sysId");
		String orgId = ThreadContextHelper.getOrgId();
		List<Map<String, Object>> tableList = this.reportManagerServices.findTablesByNodeId(nodeId, orgId);
		String[] tableIdArrays = new String[tableList.size()];
		String tableName = "";
		for (int i = 0; i < tableList.size(); i++) {
			Map<String, Object> tableMap = tableList.get(i);
			tableIdArrays[i] = (String) tableMap.get("ID");
			tableName += (String) tableMap.get("TABLE_NAME");
			if (i != tableList.size() - 1) {
				tableName += ",";
			}
		}

		List<Map<String, Object>> columnAllList = new ArrayList<Map<String, Object>>();

		String tmpTableName = "";
		for (String tmptableId : tableIdArrays) {
			// 调用接口获取库表数据
			List<Map<String, Object>> list = commTableManagerIntfsService.getCbbTableAndColumnsByTabIdByIntfs(tmptableId);
			String tableTitle = "";
			if (list.size() > 0) {
				tmpTableName = (String) list.get(0).get("TABLE_NAME");
				tableTitle = (String) list.get(0).get("TABLE_TITLE");
			} else {
				map.put("rows", new ArrayList<Map<String, Object>>());
				map.put("setFields", new ArrayList<Map<String, Object>>());
				return map;
			}

			List<Map<String, Object>> columnList = commTableManagerIntfsService.getCbbTabColumnsByIsAllByIntfs(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(), sysId, tmptableId, "N");

			for (Map<String, Object> column : columnList) {
				column.put("TABLE_NAME", tmpTableName);
				column.put("TABLE_TITLE", tableTitle);
			}
			columnAllList.addAll(columnList);
		}

		if (columnAllList.size() > 0) {
			Map<String, Object> firstColumn = new HashMap<String, Object>();
			firstColumn.put("COL_NAME", "");
			firstColumn.put("COL_LABEL", "(空)");
			columnAllList.add(0, firstColumn);
		}

		if (null == resultDataSource || null == templateId) {
			map.put("rows", columnAllList);
			map.put("setFields", new ArrayList<Map<String, Object>>());
			return map;
		}
		Map<String, String> argsMaps = new HashMap<String, String>();
		argsMaps.put("sysId", sysId);
		argsMaps.put("reportId", templateId);
		argsMaps.put("tableName", tableName);
		argsMaps.put("orgId", orgId);

		// 已配置字段
		List<Map<String, Object>> setFieldList = reportManagerServices.findReportSetField(argsMaps);

		List<Map<String, Object>> configList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> unConfigList = new ArrayList<Map<String, Object>>();

		// 该表已经配置过字段了，需要将已配置的字段去掉
		for (Map<String, Object> column : columnAllList) {
			configList.add(column);
		}
		for (Map<String, Object> setFieldMap : setFieldList) {
			setFieldMap.put("COL_LABEL", setFieldMap.get("FIELD_CHINESE"));
			setFieldMap.put("COL_NAME", setFieldMap.get("FIELD_ENGLISH"));
			unConfigList.add(setFieldMap);
		}
		Collections.sort(unConfigList, new Comparator<Map<String, Object>>() {

			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				String order1 = String.valueOf(o1.get("FIELD_SERIAL"));
				String order2 = String.valueOf(o2.get("FIELD_SERIAL"));
				int iorder1 = Integer.parseInt(order1);
				int iorder2 = Integer.parseInt(order2);
				if (iorder1 > iorder2) {
					return 1;
				} else {
					if (iorder1 < iorder2) {
						return -1;
					}
				}
				return 0;
			}
		});
		map.put("rows", configList);
		map.put("setFields", unConfigList);
		return map;
	}

	/**
	 * 根据表ID获取模板配置的字段信息和未配置的字段并排序
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/getTableListByTableIds")
	@ResponseBody
	public Map<String,Object> getTableListByTableIds(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String sysId = request.getParameter("sysId");
		String orgId = ThreadContextHelper.getOrgId();
		String tableIds = request.getParameter("tableIds");
		String templateId = request.getParameter("templateId");

		if (null == tableIds) {
			map.put("rows", new ArrayList<Map<String, Object>>());
			return map;
		}

		// 调用接口获取库表数据
		String[] tableIdss = tableIds.split(",");
		List<Map<String, Object>> columnAllList = new ArrayList<Map<String, Object>>();
		String tableName = "";
		String tmpTableName = "";
		for (String tableId : tableIdss) {
			// 调用接口获取库表数据
			List<Map<String, Object>> list = commTableManagerIntfsService.getCbbTableAndColumnsByTabIdByIntfs(tableId);
			String tableTitle = "";
			if (list.size() > 0) {
				tmpTableName = (String) list.get(0).get("TABLE_NAME");
				tableTitle = (String) list.get(0).get("TABLE_TITLE");
			} else {
				map.put("rows", new ArrayList<Map<String, Object>>());
				map.put("setFields", new ArrayList<Map<String, Object>>());
				return map;
			}

			List<Map<String, Object>> columnList = commTableManagerIntfsService.getCbbTabColumnsByIsAllByIntfs(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(), sysId, tableId, "N");

			for (Map<String, Object> column : columnList) {
				column.put("TABLE_NAME", tmpTableName);
				column.put("TABLE_TITLE", tableTitle);
			}
			tableName = tableName + tmpTableName + ",";
			columnAllList.addAll(columnList);
			// }

		}
		if (columnAllList.size() > 0) {
			Map<String, Object> firstColumn = new HashMap<String, Object>();
			firstColumn.put("COL_NAME", "");
			firstColumn.put("COL_LABEL", "(空)");
			columnAllList.add(0, firstColumn);
		}

		if (!"".equals(tableName)) {
			tableName = tableName.substring(0, tableName.length() - 1);
		}

		Map<String, String> argsMaps = new HashMap<String, String>();
		argsMaps.put("sysId", sysId);
		argsMaps.put("orgId", orgId);
		argsMaps.put("reportId", templateId);
		argsMaps.put("tableName", tableName);
		// 已配置字段
		List<Map<String, Object>> setFieldList = reportManagerServices.findReportSetField(argsMaps);
		List<Map<String, Object>> configList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> unConfigList = new ArrayList<Map<String, Object>>();

		// 该表已经配置过字段了，需要将已配置的字段去掉
		for (Map<String, Object> column : columnAllList) {
			configList.add(column);
		}
		for (Map<String, Object> setFieldMap : setFieldList) {
			setFieldMap.put("COL_LABEL", setFieldMap.get("FIELD_CHINESE"));
			setFieldMap.put("COL_NAME", setFieldMap.get("FIELD_ENGLISH"));
			unConfigList.add(setFieldMap);
		}
		Collections.sort(unConfigList, new Comparator<Map<String, Object>>() {

			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				String order1 = String.valueOf(o1.get("FIELD_SERIAL"));
				String order2 = String.valueOf(o2.get("FIELD_SERIAL"));
				int iorder1 = Integer.parseInt(order1);
				int iorder2 = Integer.parseInt(order2);
				if (iorder1 > iorder2) {
					return 1;
				} else {
					if (iorder1 < iorder2) {
						return -1;
					}
				}
				return 0;
			}
		});
		map.put("rows", configList);
		map.put("setFields", unConfigList);
		return map;
	}

	/**
	 * 前台展开时异步加载树
	 * @author 刘中华
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/findChildsByNodeId")
	@ResponseBody
	public Map<String,Object> findChildsByNodeId(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String,Object> maps = new HashMap<>();

		List<TreeNode> nodes = new ArrayList<TreeNode>();
		try {
			int level = 1;
			// 默认为根节点
			if (StringUtils.isEmpty(id)) {
				// String deptId = SessionHelper.getCurrentDeptId();
				id = "ROOT";
			}

			// 第一次加载展开2层
			if ("ROOT".equals(id)) {
				level = 2;
			}

			nodes = this.reportManagerServices.recurFindTreeNodesByParentId(id, level, ThreadContextHelper.getOrgId());
			if ("ROOT".equals(id)) {
				List<Map<String, Object>> publicFieldList = this.reportManagerServices.getPublicFieldInfo();
				Map<String, Object> modelMap = new HashMap<String, Object>();
				Map<String, Object> FolderMap = new HashMap<String, Object>();
				for (int i = 0; i < publicFieldList.size(); i++) {
					Map<String, Object> map = publicFieldList.get(i);
					String archiveType = (String) map.get("ARCHIVE_TYPE");
					if ("-1".equals(archiveType)) {
						modelMap = map;
					} else {
						FolderMap = map;
					}
				}
				TreeNode model = new TreeNode();
				String ridModel = (String) modelMap.get("ID");
				String rnameModel = (String) modelMap.get("ARCHIVE_CLASS_NODE_NAME");
				String parentIdModel = (String) modelMap.get("PARENT_ID");
				model.setId(ridModel);
				model.setText(rnameModel);
				model.setAttributes(modelMap);
				model.set_parentId(parentIdModel);
				model.setIconCls("icon-im-newntable");
				TreeNode folder = new TreeNode();
				String rid = (String) FolderMap.get("ID");
				String rname = (String) FolderMap.get("ARCHIVE_CLASS_NODE_NAME");
				String parentId = (String) FolderMap.get("PARENT_ID");
				folder.setId(rid);
				folder.setText(rname);
				folder.setAttributes(FolderMap);
				folder.set_parentId(parentId);
				folder.setState("closed");
				folder.setIconCls("icon-im-newnmodulelib");
				folder.getChildren().add(model);
				nodes.get(0).getChildren().add(folder);
			}
			maps.put("flag", OpResult.success);
		} catch (Exception e) {
			maps.put("flag", OpResult.failure);
			maps.put("msg", "后台处理异常，" + e.getMessage());
		}
		maps.put("data", nodes);
		return maps;
	}

	/**
	 * 跳转到配置页面
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/toConfigJsp")
	public ModelAndView toConfigJsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();

		String sysId = request.getParameter("sysId");
		String dialogId = request.getParameter("dialogId");
		// 获取模板ID
		String templateId = request.getParameter("templateId");
		// GET请求需要转码
		String outPutFields = URLDecoder.decode(request.getParameter("outPutFields"), "utf-8");
		List<?> lrfList = reportManagerServices.getListByColumnValue(LantopReportField.class, "reportId", templateId);
		if (lrfList.size() == 0) { // 没有配置过字段信息，进行配置
			reportManagerServices.saveLantopReportField(sysId, templateId, outPutFields);
		}
		mav.addObject("dialogId", dialogId);
		mav.addObject("sysId", sysId);
		mav.addObject("outputFields", outPutFields);
		mav.addObject("templateId", templateId);
		mav.addObject("fieldsCount", outPutFields.split(",").length);
		mav.setViewName("avicit/im/lantop/basic/reportmanager/ReportConfiguration");
		return mav;
	}

	/**
	 * 报表模板配置规则查询
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/getReportConfig")
	@ResponseBody
	public Map<String,Object> getReportConfig(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String configType = request.getParameter("configType");
		String templateId = request.getParameter("templateId"); // 进行先查询主表配置规则表id
		String sysId = request.getParameter("sysId");
		String orgId = ThreadContextHelper.getOrgId();
		Map<String, Object> tMap = new HashMap<String, Object>();
		// 添加查询条件
		if (null != configType && !"".equals(configType)) {
			tMap.put("filter_EQ_configType", configType);
		}
		if (null != sysId && !"".equals(sysId)) {
			tMap.put("filter_EQ_sysId", sysId);
		}
		if (null != orgId && !"".equals(orgId)) {
			tMap.put("filter_EQ_orgId", orgId);
		}
		String pageNo = request.getParameter("page");
		String pageSize = request.getParameter("rows");
		Paging<LantopReportConfigDetails> page = new Paging<LantopReportConfigDetails>();
		page.setPageNo(ComUtil.getPageNo(pageNo));
		page.setPageSize(ComUtil.getPageSize(pageSize));
		// 根据模板id查询报表配置主表id
		String reportConfigPid = reportManagerServices.findLantopReportConfigurationByTemplateId(templateId);
		if (reportConfigPid != null) {
			tMap.put("filter_EQ_reportConfigId", reportConfigPid);
			page = reportManagerServices.getReportConfig(page, tMap);
			map.put("total", page.getTotalCount());
			map.put("rows", page.getResult());
		} else {
			map.put("total", 0);
			map.put("rows", new ArrayList<Map<String, Object>>());
		}
		LOGGER.info("成功获取报表模板配置规则数据");
		return map;
	}

	/**
	 * 报表模板配置规则保存
	 * 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/saveReportGroupConfig")
	@ResponseBody
	public Map<String,Object> saveReportGroupConfig(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String configType = request.getParameter("configType");
		String templateId = request.getParameter("templateId");
		String sysId = request.getParameter("sysId");
		String orgId = ThreadContextHelper.getOrgId();
		String deptId = ThreadContextHelper.getDeptId();
		SysUser su = SessionHelper.getLoginSysUser(request);
		String secretLevel = su.getSecretLevel();
		String json = ComUtil.replaceNull2Space(request.getParameter("datas"));

		// 查询是否保存过主表，没有则先保存主表数据
		String reportConfigPid = reportManagerServices.findLantopReportConfigurationByTemplateId(templateId);
		while (reportConfigPid == null) {
			LantopReportConfiguration dto = new LantopReportConfiguration();
			dto.setOrgId(orgId);
			dto.setDeptId(deptId);
			dto.setSysId(sysId);
			dto.setSecretLevel(secretLevel);
			dto.setReortTemplateId(templateId);
			reportManagerServices.saveLantopReportConfiguration(dto);
			reportConfigPid = this.reportManagerServices.findLantopReportConfigurationByTemplateId(templateId);
		}

		// 保存子表数据
		LantopReportConfigDetails[] dtoList = JsonUtils.newInstance().Json2Bean2DataGrid(json, LantopReportConfigDetails[].class);
		for (LantopReportConfigDetails lantopReportConfigDetails : dtoList) {
			if (lantopReportConfigDetails.getId() == null) { // 新增
				lantopReportConfigDetails.setOrgId(orgId);
				lantopReportConfigDetails.setDeptId(deptId);
				lantopReportConfigDetails.setSysId(sysId);
				lantopReportConfigDetails.setSecretLevel(secretLevel);
				lantopReportConfigDetails.setReportConfigId(reportConfigPid);
				lantopReportConfigDetails.setConfigType(configType);
				reportManagerServices.saveReportConfig(lantopReportConfigDetails);
			} else { // 修改
				reportManagerServices.updateReportConfig(lantopReportConfigDetails);
			}
		}
		map.put("result", OpResult.success.toString());
		LOGGER.info("成功获取报表模板分组配置数据");
		return map;
	}

	/**
	 * 报表模板配置规则删除
	 * 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/deleteReportGroupConfig")
	@ResponseBody
	public Map<String,Object> deleteReportGroupConfig(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		try {
			String ids = request.getParameter("ids");
			String[] idArray = ids.split(",");
			if (ids != null && !"".equals(ids)) {
				String reportConfigPid = reportManagerServices.findLantopReportConfigurationIdById(idArray[0]);
				reportManagerServices.deleteReportConfigByIds(ids);
				// 当子表中无数据时，删除主表对应数据
				int count = reportManagerServices.findLantopReportConfigDetailsByPid(reportConfigPid);
				if (count == 0) {
					reportManagerServices.deleteLantopReportConfigurationById(reportConfigPid);
				}
				map.put("flag", OpResult.success);
			}
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}
		LOGGER.info("成功获取报表模板分组配置数据");
		return map;
	}

	/**
	 * 加载条件值下拉框选项
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             String
	 */
	@RequestMapping("/getConfigFieldName")
	public String getCondValue(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String templateId = request.getParameter("templateId");
		String configType = request.getParameter("configType");

		// 获得主表id
		String pid = reportManagerServices.findLantopReportConfigurationByTemplateId(templateId);
		List<Map<String, Object>> list = null;
		if (pid != null) {
			// 获得已存在的报表配置
			list = reportManagerServices.findLantopReportConfigDetailsByTemplateId(pid, configType);
		}
		List<?> lrfList = reportManagerServices.getListByColumnValue(LantopReportField.class, "reportId", templateId);
		if (lrfList.size() > 0) {
			// 前台combox下拉内容
			StringBuffer sb = new StringBuffer();
			String sbString = "";
			for (int i = 0; i < lrfList.size(); i++) {
				LantopReportField lrf = (LantopReportField) lrfList.get(i);
				boolean flag = true;
				if (list != null && list.size() > 0) {
					for (Map<String, Object> map : list) {
						String temp = (String) map.get("CONFIG_FIELD_NAME");
						if (lrf.getFieldChinese().equals(temp)) {
							flag = false;
						}
					}
				}
				if (flag) {
					sb.append("{\"id\":\"" + i + "\",");
					sb.append("\"text\":\"" + lrf.getFieldChinese() + "\"},");
				}
			}
			sbString = sb.substring(0, sb.length() - 1);
			sbString = "[" + sbString + "]";
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.write(sbString);
			out.close();
		}
		return null;
	}

	/**
	 * 报表模板分组/统计 分页查询
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/getLantopReportConfigDetailssByPage")
	public ModelAndView togetLantopReportConfigDetailsByPage(PageParameter pageParameter, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();

		return mav;
	}

}
